package com.jhd.fuzhou.util;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;

import com.alibaba.fastjson.JSON;
import com.jhd.fuzhou.view.login.FuzhouApplication;
import com.jhd.fuzhou.R;
import com.jhd.fuzhou.service.ProcessService;
import com.jhd.fuzhou.vo.JsonForResult;
import com.jhd.fuzhou.vo.PersonInfoVo;
import com.jhd.fuzhou.vo.ProInstance;
import com.jhd.fuzhou.vo.Process;

import net.zigin.commons.util.ParamsMapUtil;
import net.zigin.commons.util.StringUtil;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

import static android.app.Activity.RESULT_OK;

/*开启流程*/
public class StartProcess {

    private static AlertDialog _alertDialog;

    public static void getProInstanceId(FuzhouApplication application, String id, String status, TextView tv_process_status, TextView tv_process_reason, TextView tv_process_person, TextView tv_process_date, Context context){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        ProcessService vs = retrofit.create(ProcessService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("businessKey",id);
        Call<JsonForResult> jsonForResultCall = vs.getProInstanceId(application.getAccessToken(),application.getUserName(),params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if(jsonForResult.getData()!=null){
                            ProInstance proInstance= JSON.parseObject(jsonForResult.getData().toString(), ProInstance.class);
                            list(application,proInstance.getProcessInstanceId(),status,tv_process_status,tv_process_reason,tv_process_person,tv_process_date,context);
                        }
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }

    public static void list(FuzhouApplication application, String procInstId,String status, TextView tv_process_status,TextView tv_process_reason,TextView tv_process_person,TextView tv_process_date,Context context){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        ProcessService vs = retrofit.create(ProcessService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("procInstId",procInstId);
        Call<JsonForResult> jsonForResultCall = vs.list(application.getAccessToken(),application.getUserName(),params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if(jsonForResult.getData()!=null){
                            List<Process> processList = JSON.parseArray(jsonForResult.getData().toString(), Process.class);
                            if(processList!=null&&processList.size()>1){
                                Process process=processList.get(processList.size()-2);
                                if("分管领导审核".equals(process.getTaskName())&&"已驳回".equals(status)){
                                    tv_process_status.setText("分管领导审核已撤销");
                                }
                                tv_process_reason.setText(process.getMessage());
                                tv_process_person.setText(process.getName());
                                tv_process_date.setText(process.getStartTime());
                            }
                        }
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }

    public static void start(FuzhouApplication application,String businessKey,String type, Context context){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        ProcessService vs = retrofit.create(ProcessService.class);
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        HashMap map=new HashMap();
        map.put("type",type);
        params.put("assignees",application.getUserName());
        params.put("businessKey",businessKey);
        params.put("businessRoute","CheckTask");
        params.put("variables",map);
        RequestBody requestBody = RequestBody.create(MediaType.parse("Content-Type, application/json"), JSON.toJSONString(params));
        String json=JSON.toJSONString(params);
        Call<JsonForResult> jsonForResultCall = vs.start(application.getAccessToken(),application.getUserName(),requestBody);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if(jsonForResult.getData()!=null){
                            alertMsg(application,jsonForResult.getData().toString(),type,context);
                        }
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }

    public static void alertMsg(FuzhouApplication application, String taskId, String type, Context context) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("保存成功，是否提交审批?");
        builder.setMessage("提交后不可再更改");
        builder.setIcon(R.mipmap.dialog_alert);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                getTaskApproveLeve1(application,taskId,type,context);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                /*if(!StringUtil.isNullOrEmpty(type)){
                    CustomToast.showText(context,"添加"+type+"成功！",3000,0,0).show();
                }else{
                    CustomToast.showText(context,"添加成功！",3000,0,0).show();
                }*/
                application.exitStep();
            }
        });
        Dialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);
        if (!((Activity) context).isFinishing()) dialog.show();
        int color = context.getResources().getColor(R.color.header);
        Button btn = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
        Button btn2 = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_NEGATIVE);
        if (btn != null) btn.setTextColor(color);
        if (btn2 != null) btn2.setTextColor(color);
    }
    /*修改的*/
    public static void alertMsg2(FuzhouApplication application,String taskId, String id, String approvalStatus, String type, Context context) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("修改成功，是否提交审批?");
        builder.setMessage("提交后不可再更改");
        builder.setIcon(R.mipmap.dialog_alert);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                getTaskApproveLeve11(application,taskId,id,approvalStatus,type,context);
                updateSuperviseInspectionById(application,id,approvalStatus,type,context);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                /*if(!StringUtil.isNullOrEmpty(type)){
                    CustomToast.showText(context,"添加"+type+"成功！",3000,0,0).show();
                }else{
                    CustomToast.showText(context,"添加成功！",3000,0,0).show();
                }*/
                application.exitStep();
            }
        });
        Dialog dialog = builder.create();
        if (!((Activity) context).isFinishing()) dialog.show();
        int color = context.getResources().getColor(R.color.header);
        Button btn = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
        Button btn2 = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_NEGATIVE);
        if (btn != null) btn.setTextColor(color);
        if (btn2 != null) btn2.setTextColor(color);
    }

    public static void getTaskApproveLeve1(FuzhouApplication application,String taskId,String type, Context context){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        ProcessService vs = retrofit.create(ProcessService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("username",application.getName()).addParam("userId",application.getUserId());
        Call<JsonForResult> jsonForResultCall = vs.getTaskApproveLeve1(application.getAccessToken(),params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if(jsonForResult.getData()!=null){
                            List<PersonInfoVo> personInfoVos= JSON.parseArray(jsonForResult.getData().toString(), PersonInfoVo.class);
                            completeByAssign(application,personInfoVos.get(0).getUserName(),taskId,type,null,null,context);
                        }
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
    public static void getTaskApproveLeve11(FuzhouApplication application,String taskId,String id,String approvalStatus,String type, Context context){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        ProcessService vs = retrofit.create(ProcessService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("username",application.getName()).addParam("userId",application.getUserId());
        Call<JsonForResult> jsonForResultCall = vs.getTaskApproveLeve1(application.getAccessToken(),params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if(jsonForResult.getData()!=null){
                            List<PersonInfoVo> personInfoVos= JSON.parseArray(jsonForResult.getData().toString(), PersonInfoVo.class);
                            completeByAssignUpdate(application,personInfoVos.get(0).getUserName(),taskId,null,null,id,approvalStatus,type,context);
                        }
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }

    public static void completeByAssign(FuzhouApplication application,String assignees,String taskId,String type,String message,Map<String, Object> variables, Context context){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        ProcessService vs = retrofit.create(ProcessService.class);
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        params.put("assignees",assignees);
        params.put("taskId",taskId);
        if(!StringUtil.isNullOrEmpty(message))params.put("message",message);
        if(variables!=null)params.put("variables",variables);
        RequestBody requestBody = RequestBody.create(MediaType.parse("Content-Type, application/json"), JSON.toJSONString(params));
        String json=JSON.toJSONString(params);
        Call<JsonForResult> jsonForResultCall = vs.completeByAssign(application.getAccessToken(),application.getUserName(),requestBody);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if(!StringUtil.isNullOrEmpty(type)){
                            CustomToast.showText(context,"添加"+type+"成功！",3000,0,0).show();
                        }else{
                            CustomToast.showText(context,"添加成功！",3000,0,0).show();
                        }
                        application.exitStep();
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
    public static void updateSuperviseInspectionById(FuzhouApplication application,String id,String approvalStatus,String type, Context context){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        ProcessService vs = retrofit.create(ProcessService.class);
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        params.put("id",id);
        params.put("approvalStatus",approvalStatus);
        RequestBody requestBody = RequestBody.create(MediaType.parse("Content-Type, application/json"), JSON.toJSONString(params));
        String json=JSON.toJSONString(params);
        Call<JsonForResult> jsonForResultCall = vs.updateSuperviseInspectionById(application.getAccessToken(),requestBody);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        Intent intent = new Intent();
                        intent.putExtra("position","1");
                        ((Activity)context).setResult(RESULT_OK, intent);
                        ((Activity)context).finish();
                        CustomToast.showText(context,type,3000,0,0).show();
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
    public static void completeByAssignUpdate(FuzhouApplication application,String assignees,String taskId,String message,Map<String, Object> variables,String id,String approvalStatus,String type, Context context){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        ProcessService vs = retrofit.create(ProcessService.class);
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        params.put("assignees",assignees);
        params.put("taskId",taskId);
        if(!StringUtil.isNullOrEmpty(message))params.put("message",message);
        if(variables!=null)params.put("variables",variables);
        RequestBody requestBody = RequestBody.create(MediaType.parse("Content-Type, application/json"), JSON.toJSONString(params));
        String json=JSON.toJSONString(params);
        Call<JsonForResult> jsonForResultCall = vs.completeByAssign(application.getAccessToken(),application.getUserName(),requestBody);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        updateSuperviseInspectionById(application,id,approvalStatus,type,context);
                        application.exitStep();
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
    /*type用于update里的toast*/
    public static void completeByAssign2(FuzhouApplication application,String assignees,String taskId,String message,Map<String, Object> variables,String id,String approvalStatus,String type, Context context){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        ProcessService vs = retrofit.create(ProcessService.class);
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        params.put("assignees",assignees);
        params.put("taskId",taskId);
        if(!StringUtil.isNullOrEmpty(message))params.put("message",message);
        if(variables!=null)params.put("variables",variables);
        RequestBody requestBody = RequestBody.create(MediaType.parse("Content-Type, application/json"), JSON.toJSONString(params));
        String json=JSON.toJSONString(params);
        Call<JsonForResult> jsonForResultCall = vs.completeByAssign(application.getAccessToken(),application.getUserName(),requestBody);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        updateSuperviseInspectionById(application,id,approvalStatus,type,context);
                        application.exitTask();
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
}
